// Modules to control application life and create native browser window
const {app, BrowserWindow, Menu, MenuItem, globalShortcut} = require('electron');
const path = require('path')

let mainWindow = null;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1366,
    height: 768,
    minWidth: 1366,
    minHeight: 768,
    minimizable: false,

    fullscreen: true,
    autoHideMenuBar: true,
    alwaysOnTop: true,
    skipTaskbar: false,
    title: "魔兽世界线下活动",
    icon: "act.png",
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      devTools: false,
      nodeIntegration: true,
      sandbox: true,
      javascript: true,
      webSecurity: true,
      autoplayPolicy: "no-user-gesture-required"
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile('index.html');
  // mainWindow.loadURL("http://192.168.1.100:8090/");

  mainWindow.webContents.on('did-finish-load', () => {
    fetchDataWorker();
  });

  // Open the DevTools.
  // mainWindow.webContents.openDevTools();



  const menu = new Menu()
  menu.append(new MenuItem({
    label: '退出',
    submenu: [{
      role: 'help',
      accelerator: process.platform === 'darwin' ? 'Alt+Cmd+Q' : 'Alt+Shift+Q',
      click: () => { app.quit(); }
    }]
  }))

  Menu.setApplicationMenu(menu);
}

let fetchDataWorker = function () {
  console.log("-------------fetchDataWorker-------------");
    const {net} = require("electron");
    const request = net.request({
      method: "method",
      url: "https://h5.minweb.top/21_moshou/api"
    });
    request.on('response', (response) => {
      console.log(`STATUS: ${response.statusCode}`)
      console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
      response.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
        console.log("data:", JSON.parse(String(chunk)));
        const data = JSON.parse(String(chunk));
        let item1 = Number(data.item_1);
        let item2 = Number(data.item_2);
        let percentData = {
          left: (Number(item2 / (item1 + item2)) * 100 ).toFixed(0), // 蓝色数据
          right: (Number(item1 / (item1 + item2)) * 100 ).toFixed(0) // 红色数据
        }
        console.log(percentData);
        // 模拟测试数据
        // percentData.left = Number(Math.random() * 70 + 10).toFixed(0);
        // percentData.right = 100 - percentData.left;
        mainWindow.webContents.send('ping', JSON.stringify(percentData));
        setTimeout(fetchDataWorker.bind(this), 3 * 1000);
        // resolve(percentData);
      });
      response.on('end', () => {
        console.log('No more data in response.');
      });
    });
    request.on("error", (error) => {
      console.error(error);
      fetchDataWorker();
    });
    request.end();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  });

  globalShortcut.register('Alt+Shift+Q', () => {
    console.log('Electron loves global shortcuts!');
    app.close();
    app.quit();
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
